const App = getApp();
Page({
  /**
   * 页面的初始数据
   */
  onShareAppMessage() {
    return {
      title: 'picker-view',
      path: 'page/component/pages/picker-view/picker-view'
    }
  },
  data: {
    isLogin: false,
    userbirthday:"2000-01-01", //生日
    add_date:"2010-01-01", //入会时间
    avatarUrl:"/images/default-avatar.jpg",
    identityList:[],
    areaList:[],
    typeList:[],
    index: 0,
    tindex: 0,
    aindex: 0,
    userSex:"1",  //性别
    fileList: [],
    logoFileList: [],
    type:2,//2商会3私董会
    scrollHeight: null,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if(options['type']){
      this.setData({
        type: options['type'],
        tindex:1,
      });
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let that = this;
    that.setData({
      isLogin: App.checkIsLogin()
    });
    if (that.data.isLogin) {
     // 获取基本信息
     that.getIdentity()
     //设置列表高度
     that.setListHeight()
    }
  },
  bindPickerChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index: e.detail.value
    })
  },
  bindPickerChangeA: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      aindex: e.detail.value
    })
  },
  bindPickerChangeT: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      tindex: e.detail.value
    })
  },

  //性别
  radioChange(e) {
    console.log('radio发生change事件，携带value值为：', e.detail.value)
    this.setData({
      userSex:e.detail.value
    })
  },
  // 身份列表
  getIdentity(){
    let that = this;
    App._get('apply/identity', {}, result => {
      console.log(result.data)
      that.setData({
        identityList: result.data.Lidentity,
        areaList: result.data.area,
        typeList: result.data.type,
      }); 
    });
  },
  //提交
  formSubmit(e) {
    var formData=e.detail.value;//获取表单数据
    if(formData.shanghui_name == ""){
      App.showError("商会名称不能空!");
      return;
    }
    if(!this.data.logoFileList.length){
      App.showError("商会LOGO不能空!");
      return;
    }
    if(!this.data.fileList.length){
      App.showError("商会证件照不能空!");
      return;
    }
    let obj = {
      shanghui_name:formData.shanghui_name, //商会名称
      nickName:formData.userName, //联系人
      phone:formData.userTel,  //电话
      birth_date:this.data.userbirthday,//生日
      gender:this.data.userSex,//性别
      identity:this.data.identityList[this.data.index], //身份
      area:this.data.areaList[this.data.aindex], //地区
      type:this.data.typeList[this.data.tindex], //社团性质
      add_date:this.data.add_date,//入会时间
      userNumber:formData.userNumber,//身份证
      image_id:this.data.fileList[0].file_id, //图片ID
      logo_id:this.data.logoFileList[0].file_id, //LOGO图片ID
    };
    if(obj.nickName == ''){
      App.showError("联系人不能空！");
      return;
    }
    if(obj.phone.length <11){
      App.showError("请输入正确手机号！");
      return;
    }
    let _this = this;
    App._post_form('apply/add_shanghui', obj, result => {
      if(result.code == 1){
        //成功提示
        App.showSuccess(result.msg, function() {
          wx.navigateTo({
            url: '/pages/index/index',
          })
        });
      }else{
        App.showError(result.msg);
      }
    });
  },

  // 删除照片
  deleteClick(event) {
    var imgData = this.data.fileList;
    // 通过splice方法删除图片
    imgData.splice(event.detail.index, 1);
    // 更新图片数组
    this.setData({
        fileList: imgData
    })
    console.log(this.data.fileList)
  },
  // 图片上传
  afterRead(event) {
    let that = this;
    // loading加载
    wx.showLoading({title: '上传中...'});
    //获取图片详细信息
    const {file} = event.detail;
    //调用上传图片方法
    that.uploadCompressImg(file).then(res=>{
      App.uploadFile(res,{},function(result){
        const fileList = [];
        // // 将图片信息添加到fileList数字中
        fileList.push({
            url: result.data.file_path,
            file_id:result.data.file_id,
        });
        // 更新存放图片的数组
        that.setData({
            fileList
        });
        wx.hideLoading();//停止loading
      })
    })

  },
  // 删除照片
  logoDeleteClick(event) {
    var imgData = this.data.logoFileList;
    // 通过splice方法删除图片
    imgData.splice(event.detail.index, 1);
    // 更新图片数组
    this.setData({
      logoFileList: imgData
    })
    console.log(this.data.logoFileList)
  },
  // 图片上传
  logoAfterRead(event) {
    let that = this;
    // loading加载
    wx.showLoading({title: '上传中...'});
    //获取图片详细信息
    const {file} = event.detail;
    //调用上传图片方法
    that.uploadCompressImg(file).then(res=>{
      App.uploadFile(res,{},function(result){
        const fileList = [];
        // // 将图片信息添加到fileList数字中
        fileList.push({
            url: result.data.file_path,
            file_id:result.data.file_id,
        });
        // 更新存放图片的数组
        that.setData({
          logoFileList:fileList
        });
        wx.hideLoading();//停止loading
      })
    })

  },
  //生日
  bindDateChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      userbirthday: e.detail.value
    })
  },
  //入会时间
  bindDateChange1: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      add_date: e.detail.value
    })
  },
    //设置列表高度
    setListHeight() {
      let systemInfo = wx.getSystemInfoSync(),
        rpx = systemInfo.windowWidth / 750, // 计算rpx
        tapHeight = Math.floor(rpx * 178), // tap高度
        scrollHeight = systemInfo.windowHeight - tapHeight; // swiper高度
      this.setData({
        scrollHeight
      });
    },
    //图片压缩
    uploadCompressImg(file) {
      let that = this
      return new Promise(function(resolve, reject){
        let file_url = file.tempFilePath
        console.log(file);
        if(file.size < 500*1024){
          console.log("size",file.size)
          console.log("file_url",file_url)
          resolve(file_url);
        }else{
            // 获得原始图片大小
            wx.getImageInfo({
              src: file_url,
              success(res) {
                console.log(res);
              
                let originHeight = res.height;
                let originWidth = res.width;
                // 压缩比例
                // 最大尺寸限制
                let maxWidth = 1024,
                  maxHeight = 1024;
                // 目标尺寸
                let targetWidth = originWidth,
                  targetHeight = originHeight;
                // 等比例压缩，如果宽度大于高度，则宽度优先，否则高度优先
                if (originWidth > maxWidth || originHeight > maxHeight) {
                  if (originWidth / originHeight > maxWidth / maxHeight) {
                    // 要求宽度*(原生图片比例)=新图片尺寸
                    targetWidth = maxWidth;
                    targetHeight = Math.round(maxWidth * (originHeight / originWidth));
                  } else {
                    targetHeight = maxHeight;
                    targetWidth = Math.round(maxHeight * (originWidth / originHeight));
                  }
                }
  
                // 更新 canvas 大小
                that.setData({
                  "cw": targetWidth,
                  "ch": targetHeight
                });
                // 尝试压缩文件，创建 canvas
                let ctx = wx.createCanvasContext('canvas');
                ctx.clearRect(0, 0, targetWidth, targetHeight);
                //通过得到图片旋转的角度来调整显示方向以正确显示图片，主要解决 ios 系统上的图片会有旋转的问题
                let orientation = res.orientation;
                if (orientation == 'right') { //exif的6
                  that.setData({
                    "cw": targetHeight,
                    "ch": targetWidth
                  });
                  ctx.rotate(90 * Math.PI / 180);
                  ctx.drawImage(file_url, 0, 0, targetWidth, targetHeight, 0, -targetHeight, that.data.ch, that.data.cw);
                } else {
                  ctx.drawImage(file_url, 0, 0, targetWidth, targetHeight);
                }
  
                ctx.draw(false, function () {
                  // 获得新图片输出
                  wx.canvasToTempFilePath({
                    x: 0,
                    y: 0,
                    canvasId: 'canvas',
                    destWidth: targetWidth,
                    destHeight: targetHeight,
                    quality: 0.9,
                    fileType: "jpg",
                    success: (res) => {
                      console.log(res)
                      resolve(res.tempFilePath);
                    },
                    fail: (err) => {
                      console.error(err)
                    }
                  }, this)
                })
              }
            })
        }
      })
    },
})